<template>
  <el-form :model="form">
    <el-form-item label="登录账号" :label-width="formLabelWidth">
      <el-input v-model="form.adminname" autocomplete="off" />
    </el-form-item>
    <el-form-item label="密码" :label-width="formLabelWidth">
      <el-input type="password" v-model="form.password" autocomplete="off" />
    </el-form-item>
    <el-form-item label="角色" :label-width="formLabelWidth">
      <el-select v-model.number="form.role" placeholder="请选择角色">
        <el-option v-for="item in roles" v-bind:label="item.label" v-bind:value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="权限" :label-width="formLabelWidth">

      <el-tree ref="treeRef" :data="data" show-checkbox node-key="id">
      </el-tree>
    </el-form-item>
    <el-form-item>
      <el-button @click="addoper">添加</el-button>
      <el-button>取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
import { ref, reactive } from "vue";
import type { IOper } from "@/MyTs";  //自定义ts
import { ElMessage, ElTree } from "element-plus"; //引入element
import { AddManage } from "@/api/Login" // 引入添加接口数据
import { roles, grantsData as data } from "./data" //引入data.ts数据用于树形结构的字面量
const formLabelWidth = "140px";


interface IEmits {
  (e: "onOK"): void
  (e: "onCleas"): void
} //传递参数，没有返回值 
//子传父，在父组件的子标签上定义自定义事件，在子组件内使用emits触发事件。
const emits = defineEmits<IEmits>();//定义变量包含IEmits类型的对象用于组件事件
//定义组件接收的数据用于接口传值
const form = reactive<IOper>({
  adminname: '',
  password: "",
  role: 0,
  checkedKeys: []
})
//点击添加管理员
const addoper = () => {
  //获取树形结构选中的数据id并且让他给from中的checkedKeys赋值
  // const ADDer = treeRef.value?.getCheckedKeys();
  // form.checkedKeys = ADDer;
  const checkedKeys = (treeRef.value?.getCheckedKeys() || []);
  const halfCheckedKeys = (treeRef.value?.getHalfCheckedKeys() || []);

  form.checkedKeys = [...checkedKeys, ...halfCheckedKeys];
  AddManage(form).then(res => {


    if (res.data.code == 200) {
      ElMessage({
        message: '添加成功',
        type: 'success',
        duration: 1000
      })
      //1. 提示 2.关闭添加窗口 3. 刷新窗口
      form.adminname = "";
      form.password = "";
      form.role = 0;
      form.checkedKeys = [];
      emits("onOK")

    } else {
      ElMessage({
        message: '已经存在',
        type: 'success',
        duration: 1000
      });
      emits("onCleas")
    }
  }).catch(err => {
    alert("添加操作人员出错",)

  })
}

const treeRef = ref<InstanceType<typeof ElTree>>();
</script>
<style lang="scss" scoped>
.el-select {
  width: 300px;
}

.el-input {
  width: 300px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
